package com.sharp.portal.repository;

import com.github.pagehelper.PageInfo;
import com.sharp.kernel.constant.db.SqlConstant;
import com.sharp.kernel.mybatis.mapper.MysqlBaseMapper;
import com.sharp.kernel.mybatis.repository.BaseMysqlRepository;
import com.sharp.portal.constant.dict.PortalSortDict;
import com.sharp.portal.vo.ConditionVO;
import com.sharp.portal.vo.QueryConditionReq;
import com.sharp.portal.vo.SortVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Title: PortalRepository
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/6/13 17:11
 */
public class PortalRepository<T, K extends MysqlBaseMapper<T>> extends BaseMysqlRepository<T, K> {

    public PageInfo<T> select(QueryConditionReq req) {
        return select(req.getConditionList(), req.getSort(), req.getCurrentPage(), req.getPageSize());
    }

    public PageInfo<T> select(List<ConditionVO> conditions, SortVO sort, int currentPage, int pageSize) {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        if (CollectionUtils.isNotEmpty(conditions)) {
            for (ConditionVO condition : conditions) {
                if (StringUtils.isNotBlank(condition.getProperty())) {
                    if (StringUtils.isNotBlank(condition.getValue())) {
                        criteria = buildCriteria(example, condition.getProperty(), condition.getValue(), condition.getRelation());
                    } else if (CollectionUtils.isNotEmpty(condition.getValueList())) {
                        criteria = buildCriteria(example, condition.getProperty(), condition.getValueList(), condition.getRelation());
                    } else if (condition.getRelation().equals(SqlConstant.NOT_NULL) || condition.getRelation().equals(SqlConstant.NULL)) {
                        criteria = buildCriteria(example, condition.getProperty(), condition.getValue(), condition.getRelation());
                    }
                    example.and(criteria);
                }
            }
        }

        if (sort.getType() != null && StringUtils.isNotBlank(sort.getProperty())) {
            if (PortalSortDict.DESC.getValue().equals(sort.getType())) {
                example.orderBy(sort.getProperty()).desc();
            } else {
                example.orderBy(sort.getProperty()).asc();
            }
        }
        return select(example, currentPage, pageSize);
    }
}
